import Vue from 'vue'
import VueRouter from 'vue-router'
import my_register from '../views/register/index.vue'
import my_login from '../views/login/index.vue'
import my_layout from '@/views/layout/index.vue'
import my_home from '@/views/home/index.vue'
import userInfo from '@/views/user/userInfo.vue'
import userAvatar from '@/views/user/userAvatar.vue'
import userPwd from '@/views/user/userPwd.vue'
import artCate from '@/views/article/artCate.vue'
import artList from '@/views/article/artList.vue'
import artlistView from '@/views/article/artlistView.vue'
import store from '@/store'
Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   redirect: '/login'
  // },
  {
    path: '/reg',
    component: my_register
  },
  {
    path: '/login',
    component: my_login
  },
  {
    path: '/',
    component: my_layout,
    redirect: '/home',
    children: [
      {
        path: 'home',
        component: my_home
      },
      {
        path: 'user-info',
        component: userInfo
      },
      {
        path: 'user-avatar',
        component: userAvatar
      },
      {
        path: 'user-pwd',
        component: userPwd
      },
      {
        path: 'art-cate',
        component: artCate
      },
      {
        path: 'art-list', // 文章列表
        component: artList
      },
      {
        path: 'artlistView',
        component: artlistView
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 路由白名单
const whiteList = ['/login', '/reg']

// 全局前置路由守卫
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    if (!store.state.userInfo.username) {
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
